/**
 * 
 */
package org.xtense.model;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

/**
 * @author Owner
 * 
 */
public class CDocument extends CSubSet {
	private String documentName;

	// for read
	public CDocument(String documentName) {
		super();
		this.documentName = documentName;
	}

	// for query
	public CDocument(CSubSet set, String string) {
		super(set.getAttributes(), set.getElements(), set.getText(), set
				.getDocumentID());
		this.documentName = string;
	}

	/**
	 * @return the documentName
	 */
	public String getDocumentName() {
		return documentName;
	}

	/**
	 * @param documentName
	 *            the documentName to set
	 */
	public void setDocumentName(String documentName) {
		this.documentName = documentName;
	}

	/**
	 * Create a document.
	 * 
	 * @return Document
	 */
	public Document createXmlDocument() {
		Element root = (Element) getResultSet().get(0);// only the root
		Document document = DocumentHelper.createDocument(root);
		return document;
	}

	// private Element getXmlRoot() {
	// return getElementWithAttributeAndText(getElements().get(1));
	// }

	public void prettyWrite() throws UnsupportedEncodingException, IOException {
		OutputFormat format = OutputFormat.createPrettyPrint();
		XMLWriter writer = new XMLWriter(System.out, format);
		writer.write(createXmlDocument());
	}

	public void compactWrite() throws UnsupportedEncodingException, IOException {
		OutputFormat format = OutputFormat.createCompactFormat();
		XMLWriter writer = new XMLWriter(System.out, format);
		writer.write(createXmlDocument());
	}

	public void compactWrite(OutputStream os)
			throws UnsupportedEncodingException, IOException {
		OutputFormat format = OutputFormat.createCompactFormat();
		XMLWriter writer = new XMLWriter(os, format);
		writer.write(createXmlDocument());
	}

}
